import 'package:flutter/material.dart';
import '../models/chat_message.dart';
import '../constants/app_dimensions.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import '../constants/app_constants.dart';
import '../services/platform_service.dart';

class ChatBubble extends StatelessWidget {
  final ChatMessage message;

  const ChatBubble({
    super.key,
    required this.message,
  });

  @override
  Widget build(BuildContext context) {
    // 分离不同类型的内容
    String thinkingPart = '';
    String answerPart = message.text;
    List<String> codeBlocks = [];
    String? drawingPrompt;

    if (!message.isUser) {
      if (message.text.contains('思考过程：')) {
        final parts = message.text.split('\n\n回答：');
        if (parts.length > 1) {
          thinkingPart = parts[0].replaceFirst('思考过程：\n', '');
          answerPart = parts[1].trim();
        }
      }

      // 实时检测代码块
      String tempAnswer = answerPart;
      final codeRegex =
          RegExp(r'```[\s\S]*?```|```[\s\S]*$'); // 修改正则表达式以匹配未完成的代码块
      final matches = codeRegex.allMatches(tempAnswer);

      for (var match in matches) {
        String code = match.group(0)!;
        // 如果代码块未完成（正在输入中）
        if (!code.endsWith('```')) {
          code = '$code```'; // 临时补全结束标记以便显示
        }
        codeBlocks.add(code);
        tempAnswer = tempAnswer.replaceAll(match.group(0)!, '').trim();
      }
      answerPart = tempAnswer;

      // 检测绘画提示词
      if (answerPart.contains('绘画提示词：')) {
        final promptRegex = RegExp(r'绘画提示词：([\s\S]*?)(?=\n|$)');
        final match = promptRegex.firstMatch(answerPart);
        if (match != null) {
          drawingPrompt = match.group(1)?.trim();
          answerPart = answerPart.replaceAll('绘画提示词：$drawingPrompt', '').trim();
        }
      }
    }

    return RepaintBoundary(
      child: Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: AppDimensions.padding,
          vertical: AppDimensions.padding / 2,
        ),
        child: Column(
          crossAxisAlignment: message.isUser
              ? CrossAxisAlignment.end
              : CrossAxisAlignment.start,
          children: [
            // 思考过程气泡
            if (!message.isUser && thinkingPart.isNotEmpty)
              _buildThinkingBubble(context, thinkingPart),

            // 所有代码块气泡
            ...codeBlocks.map((code) => _buildCodeBubble(context, code)),

            // 绘画提示词气泡
            if (drawingPrompt != null)
              _buildDrawingBubble(context, drawingPrompt),

            // 普通回答气泡
            if (answerPart.isNotEmpty) _buildAnswerBubble(context, answerPart),
          ],
        ),
      ),
    );
  }

  Widget _buildCodeBubble(BuildContext context, String code) {
    // 解析代码语言
    String language = 'text';
    if (code.startsWith('```')) {
      final firstLine = code.split('\n').first;
      language = firstLine.replaceAll('```', '').trim();
      code = code.substring(code.indexOf('\n') + 1);
    }

    bool isDarkTheme = true; // 添加主题状态变量

    // Modify the action buttons based on platform
    List<Widget> actionButtons = [
      _buildActionButton(
        icon: Icons.copy,
        tooltip: '复制代码',
        onPressed: () => _copyCode(context, code),
      ),
    ];

    // Only show download button on non-web platforms
    if (PlatformService.supportsFileDownload) {
      actionButtons.add(
        PopupMenuButton<String>(
          tooltip: '下载代码',
          icon: Icon(
            Icons.download,
            size: 16,
            color: Colors.grey[400],
          ),
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'text',
              child: Row(
                children: [
                  Icon(Icons.text_fields, size: 20),
                  SizedBox(width: 8),
                  Text('下载为文本'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'file',
              child: Row(
                children: [
                  Icon(Icons.file_present, size: 20),
                  SizedBox(width: 8),
                  Text('下载为文件'),
                ],
              ),
            ),
          ],
          onSelected: (value) =>
              _handleDownload(context, value, code, language),
        ),
      );
    }

    return StatefulBuilder(
      // 将Container包装在StatefulBuilder中以管理局部状态
      builder: (context, setState) {
        return Container(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.95,
          ),
          margin: const EdgeInsets.only(bottom: 8),
          decoration: BoxDecoration(
            color: isDarkTheme ? const Color(0xFF1E1E1E) : Colors.white,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withAlpha((0.2 * 255).toInt()),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 代码标题栏
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: const BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(12),
                    topRight: Radius.circular(12),
                  ),
                ),
                child: Row(
                  children: [
                    // 语言图标和名称
                    Icon(
                      Icons.code,
                      size: 16,
                      color: Colors.blue[300],
                    ),
                    const SizedBox(width: 8),
                    Text(
                      language,
                      style: TextStyle(
                        color: Colors.grey[300],
                        fontSize: 13,
                      ),
                    ),
                    const Spacer(),
                    // 操作按钮
                    ...actionButtons,
                    _buildActionButton(
                      icon: isDarkTheme ? Icons.light_mode : Icons.dark_mode,
                      tooltip: '切换主题',
                      onPressed: () {
                        setState(() {
                          isDarkTheme = !isDarkTheme;
                        });
                      },
                    ),
                  ],
                ),
              ),
              // 代码内容
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Container(
                  padding: const EdgeInsets.all(16),
                  child: Text(
                    code.replaceAll('```', '').trim(),
                    style: TextStyle(
                      color: isDarkTheme ? Colors.grey[300] : Colors.grey[800],
                      fontSize: 14,
                      fontFamily: 'Fira Code',
                      height: 1.5,
                    ),
                  ),
                ),
              ),
              // 底部状态栏
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: const BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(12),
                    bottomRight: Radius.circular(12),
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.info_outline,
                      size: 14,
                      color: Colors.grey[400],
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '按 Ctrl+C 复制代码',
                      style: TextStyle(
                        color: Colors.grey[400],
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String tooltip,
    required VoidCallback onPressed,
  }) {
    return Tooltip(
      message: tooltip,
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(4),
          onTap: onPressed,
          child: Padding(
            padding: const EdgeInsets.all(4),
            child: Icon(
              icon,
              size: 16,
              color: Colors.grey[400],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDrawingBubble(BuildContext context, String prompt) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.95,
      ),
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.purple[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.purple.withAlpha((0.2 * 255).toInt())),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha((0.03 * 255).toInt()),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.brush,
                size: 18,
                color: Colors.purple[300],
              ),
              const SizedBox(width: 8),
              Text(
                '绘画提示词',
                style: TextStyle(
                  color: Colors.purple[300],
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const Divider(height: 16),
          Text(
            prompt,
            style: const TextStyle(
              color: Colors.black87,
              fontSize: 14,
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildThinkingBubble(BuildContext context, String thinkingPart) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.95,
      ),
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.withAlpha((0.2 * 255).toInt())),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha((0.03 * 255).toInt()),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.psychology,
                size: 18,
                color: Colors.blue[300],
              ),
              const SizedBox(width: 8),
              Text(
                '思考过程',
                style: TextStyle(
                  color: Colors.blue[300],
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const Divider(height: 16),
          Text(
            thinkingPart,
            style: const TextStyle(
              color: Colors.black87,
              fontSize: 14,
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAnswerBubble(BuildContext context, String answerPart) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.85,
      ),
      padding: const EdgeInsets.symmetric(
        horizontal: 16,
        vertical: 12,
      ),
      decoration: BoxDecoration(
        color: message.isUser
            ? AppColors.messageBubbleUser
            : AppColors.messageBubbleBot,
        borderRadius: BorderRadius.circular(16).copyWith(
          topLeft: message.isUser ? Radius.circular(16) : Radius.circular(4),
          topRight: message.isUser ? Radius.circular(4) : Radius.circular(16),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SelectableText(
            answerPart,
            style: TextStyle(
              color: message.isUser ? Colors.white : Colors.black87,
              fontSize: 15,
              height: 1.4,
            ),
          ),
          if (message.isStreaming) ...[
            const SizedBox(height: 8),
            _buildLoadingIndicator(),
          ],
        ],
      ),
    );
  }

  // 添加一个辅助方法来获取文件扩展名
  String _getFileExtension(String language) {
    switch (language.toLowerCase()) {
      case 'python':
        return '.py';
      case 'javascript':
        return '.js';
      case 'typescript':
        return '.ts';
      case 'dart':
        return '.dart';
      case 'java':
        return '.java';
      case 'kotlin':
        return '.kt';
      case 'swift':
        return '.swift';
      case 'cpp':
        return '.cpp';
      case 'c':
        return '.c';
      case 'html':
        return '.html';
      case 'css':
        return '.css';
      case 'json':
        return '.json';
      case 'xml':
        return '.xml';
      case 'yaml':
        return '.yaml';
      case 'markdown':
        return '.md';
      default:
        return '.txt';
    }
  }

  // 修改消息生成时的加载指示器显示
  Widget _buildLoadingIndicator() {
    return const SizedBox(
      width: 20, // 设置一个合适的小尺寸
      height: 20,
      child: CircularProgressIndicator(
        strokeWidth: 2, // 使用更细的线条
      ),
    );
  }

  // Add helper methods for platform-specific actions
  void _copyCode(BuildContext context, String code) {
    final cleanCode = code.replaceAll('```', '').trim();
    Clipboard.setData(ClipboardData(text: cleanCode)).then((_) {
      if (PlatformService.supportsHapticFeedback) {
        HapticFeedback.lightImpact();
      }
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('代码已复制到剪贴板'),
          duration: Duration(seconds: 2),
        ),
      );
    });
  }

  void _handleDownload(
      BuildContext context, String value, String code, String language) async {
    final cleanCode = code.replaceAll('```', '').trim();
    final currentContext = context;

    try {
      final downloadsDir = await getDownloadsDirectory();
      if (downloadsDir == null) {
        throw Exception('无法访问下载目录');
      }

      if (value == 'text') {
        final file = File('${downloadsDir.path}/code.txt');
        await file.writeAsString(cleanCode);
        if (currentContext.mounted) {
          ScaffoldMessenger.of(currentContext).showSnackBar(
            SnackBar(content: Text('文本已保存到: ${file.path}')),
          );
        }
      } else if (value == 'file') {
        final extension = _getFileExtension(language);
        final file = File('${downloadsDir.path}/code$extension');
        await file.writeAsString(cleanCode);
        if (currentContext.mounted) {
          ScaffoldMessenger.of(currentContext).showSnackBar(
            SnackBar(content: Text('文件已保存到: ${file.path}')),
          );
        }
      }
    } catch (e) {
      if (currentContext.mounted) {
        ScaffoldMessenger.of(currentContext).showSnackBar(
          SnackBar(content: Text('保存失败: $e')),
        );
      }
    }
  }
}
